package com.wanhe.viewconf.views.child;

import android.content.Context;
import android.text.TextUtils;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.wanhe.base.Const;
import com.wanhe.base.model.disgn.DSFile;
import com.wanhe.base.model.disgn.Event;
import com.wanhe.base.model.disgn.ViewEvent;
import com.wanhe.base.model.disgn.ViewItem;
import com.wanhe.base.model.holder.FileHolder;
import com.wanhe.base.util.ObjectUtil;
import com.wanhe.viewconf.views.child.MealBookChildItemView;

/**
 * File Name:MealBookImageView.java<br/>
 * Package Name:com.wanhe.viewconf.views.child.image<br/>
 * Date:2017/7/4 16:56<br/>
 * author:chendeji<br/>
 * desc: 菜单页面上的图片控件<br/>
 * Copyright (c) 2017/7/4, 781571323@qq.com All Rights Reserved.
 *
 */
public class MealBookImageView extends MealBookChildItemView {

	private ImageView	imageView;
	private String		currentFilePath;

	public MealBookImageView(Context context) {
		super(context);
	}

	@Override
	public void initModelData(ViewItem item) {
		super.initModelData(item);
		int fid = item.getFile();
		DSFile file = FileHolder.getInstance().get(fid);
		if (ObjectUtil.checkObject(file)) {
			showImage(file);
		}
	}

	private void showImage(DSFile file) {
		if (ObjectUtil.checkObject(file)) {
			String fileName = file.getFileName();
			if (fileName.equals(this.currentFilePath))
				return;
			currentFilePath = fileName;
		}
		String url = null;
		if (TextUtils.isEmpty(currentFilePath)) return;
		if (currentFilePath.endsWith("jpg") || currentFilePath.endsWith("png")) {
			url = Const.getUrl(currentFilePath, Const.imageBaseUrl);
		} else if (currentFilePath.endsWith("gif")) {
			url = Const.getUrl(currentFilePath, Const.gifBaseUrl);
		}
		if (TextUtils.isEmpty(url) || imageView == null)
			return;
		Glide.with(getContext()).load(url).diskCacheStrategy(DiskCacheStrategy.SOURCE)
				.into(imageView);
	}

	@Override
	public void show(Event event, ViewEvent.Coor coor) {
		super.show(event, coor);
		int fid = event.getArgs().getFile();
		DSFile file = FileHolder.getInstance().get(fid);
		if (ObjectUtil.checkObject(file)) {
			showImage(file);
		}
	}

	@Override
	public void hide(Event event, ViewEvent.Coor coor) {
		super.hide(event, coor);
	}

	private void initView() {
		imageView = new ImageView(getContext());
		imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT));
		addView(imageView);
	}

	@Override
	public void pause(Event event, ViewEvent.Coor coor) {
		super.pause(event, coor);
		setViewStatu(VIEW_DIRTY);
		removeAllViews();
	}

	@Override
	public void resume(Event event, ViewEvent.Coor coor) {
		super.resume(event, coor);
		setViewStatu(VIEW_DIRTY);
		initView();
		showImage(null);
	}
}
